package com.xpp.yanpicturebackend.api.imagesearch.sub;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.xpp.yanpicturebackend.exception.BusinessException;
import com.xpp.yanpicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取以图搜图页面地址
 */
@Slf4j
public class GetImagePageUrlApi {

    private static final String acs_token = "1749443158484_1749526185143_2XUjDCXkkd4t/s0qElR9t5kWapBq608KerrBm5EHsc3WTpw" +
            "Ztg0wsn28v5KPF44kiRu4ZY85il1iN6jX47RHfReRnOCNtwx/t3byohi57BnJFsqqZDlxlHuJFnzOjyBYnsmYKPtd27YZ+alXVbh/lf0891" +
            "UEyduKR3MO8Wwqmyd7ydHaZDB7+X355/2vWLrPTKodrSGF/BHQCOvR2DY98dzafZ7V/1od4zDqG65/hC2T41EFxXsPPUYK/n6CK1uuKPK3P" +
            "fEz8WcpnvMlkw5cTW4U+m8r4AkopmrzrcrKNHjsvnwSu4KWRZd4HK8bNSjKqmf02qmbYrrRDKZSUpcfSjAEmFVs5hEnmR0aoPRgZPpFgTEi" +
            "JKja6BlJrBm7u23Q+DM70DpHO8r/+fNJ/25SU8tUZJgKe6Mm/aOJujlAhDxpS3kiqw6V4Nc82jCEu7hE";

    /**
     * 获取以图搜图的页面地址
     *
     * @param imageUrl
     * @return
     */
    public static String getImagePageUrl(String imageUrl) {
        // 1.准备请求参数
        Map<String, Object> formData = new HashMap<>();
        formData.put("image", imageUrl);
        formData.put("tn", "pc");
        formData.put("from", "pc");
        formData.put("image_source", "PC_UPLOAD_URL");
        // 获取当前时间戳
        long uptime = System.currentTimeMillis();
        // 请求地址
        String url = "https://graph.baidu.com/upload?uptime=" + uptime;
        String searchResultUrl = null;

        try {
            // 2. 发送请求
            HttpResponse httpResponse = HttpRequest.post(url)
                    .header("Acs_Token", acs_token)
                    .form(formData)
                    .timeout(5000)
                    .execute();
            if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
            }
            // 解析响应
            String body = httpResponse.body();
            Map<String, Object> result = JSONUtil.toBean(body, Map.class);
            // 3. 处理响应结果
            if (result == null || !Integer.valueOf(0).equals(result.get("status"))) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
            }
            Map<String, Object> data = (Map<String, Object>) result.get("data");
            // 对url进行解码
            String rawUrl = (String) data.get("url");
            searchResultUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);
            if (StrUtil.isBlank(searchResultUrl)) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "未返回有效的结果地址");
            }
            return searchResultUrl;
        } catch (Exception e) {
            log.error("getImagePageUrl error", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜索失败");
        }
    }


}
